<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############








function JFX_ExportPage_MakeTree($arr){
    $CONFIG = JFX::registry('config');
    $USER = JFX::registry('JFX_User');
    $LANG = JFX::registry('lang');
    $returnString = '';
    foreach($arr as $k=>$v){

        $link = '<a href="'.$CONFIG->adminUrl.'/export/export-page/?page='.$v['id'].'">'.$LANG->getContent('core', 'page_title', $v['id']).'</a>';
        if(isset($v['subpages']) && count($v['subpages'])>0){
            $subpages = '<ul>'.JFX_ExportPage_MakeTree($v['subpages']).'</ul>';
        }else{
            $subpages = '';
        }
        $returnString .= '<li class="redirect">'.$link.$subpages.'</li>';
    }

    return $returnString;
}






function JFX_ExportPage_CompressPage($page, &$deps){
    $DB = JFX::registry('db');
    $USER = JFX::registry('JFX_User');
    $CONFIG = JFX::registry('config');
    $LANG = JFX::registry('lang');
    $block = new JFX_Block;

    $installedLangs = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}languages");

    $newPage = array();
    $newPage['sp'] = array();
    if(count($page['subpages'])>0){
        foreach($page['subpages'] as $k=>$v){
            $newPage['sp'][] = JFX_ExportPage_CompressPage($v, $deps);
        }
    }



    $blocks = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}blocks WHERE page_id = '{$page['id']}' AND workspace_id = '{$USER->workspace}' AND parent_id = 'jfxpage-{$page['id']}' AND page_parent = 1");

    foreach($blocks as $k=>$v){
        $blocks[$k] = JFX_ExportPage_GetBlockLangs($v, $page['id'], $USER->workspace);
        if(!in_array($v['module_key'], $deps)) $deps[] = $v['module_key'];
        $params = array(
            'module_data' => array(),
            'block_id' => $v['id']
        );
        JFX::hook('JFX_Core:exportBlock', $blocks[$k]);
        $blocks[$k]['md'] = $params['module_data'];
    }

    $langs = array();

    foreach($installedLangs as $k=>$v){
        $langs[$v['keyname']] = array(
            't' => $LANG->getContent('core', 'page_title', $page['id'], $v['keyname'], $page['workspace_id']),
            'm' => $LANG->getContent('core', 'page_menu', $page['id'], $v['keyname'], $page['workspace_id']),
            'c' => $LANG->getContent('core', 'page_content', $page['id'], $v['keyname'], $page['workspace_id'])
        );
    }


    $newPage['d'] = $deps;
    $newPage['i'] = $page['id'];
    $newPage['p'] = $page['parent_id'];
    $newPage['s'] = $page['slug'];
    $newPage['l'] = $page['is_published'];
    $newPage['o'] = $page['owner_id'];
    $newPage['c'] = $page['created_tstamp'];
    $newPage['m'] = $page['modified_tstamp'];
    $newPage['t'] = $langs;
    $newPage['b'] = serialize($blocks);
    $params = array(
        'page_id' => $page['id'],
        'module_data' => array()
    );

    JFX::hook('JFX_Core.exportPage', $params);

    $newPage['md'] = $params['module_data'];




//    $newPage['b'] = $MTF->encode($BWT->transform(serialize($blocks)));

    return $newPage;
}





function JFX_ExportPage_GetBlockLangs($blockDetails, $pageid, $workspaceid){
    $USER = JFX::registry('JFX_User');
    $DB = JFX::registry('db');
    $CONFIG = JFX::registry('config');
    $block = new JFX_Block;

    $blockDetails['elements'] = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}blocks WHERE page_id = '{$pageid}' AND workspace_id = '{$workspaceid}' AND parent_id = '{$blockDetails['id']}'");

    $installedLangs = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}languages");

    $lang = array();
    foreach($installedLangs as $k=>$v){
        $langContent = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}lang_content WHERE item_id = '{$blockDetails['id']}' AND lang = '{$v['keyname']}'");
        $lang[$v['keyname']] = $langContent;
    }
    $blockDetails['lang'] = $lang;
    foreach($blockDetails['elements'] as $k=>$v){
        $blockDetails['elements'][$k] = JFX_ExportPage_GetBlockLangs($v, $pageid, $workspaceid);
    }
    if(!is_array($blockDetails)) $blockDetails = array();
    return $blockDetails;
}









function JFX_ExportBlock_GetBlockDetails($blockDetails, $pageid, $workspaceid){
    $USER = JFX::registry('JFX_User');
    $DB = JFX::registry('db');
    $CONFIG = JFX::registry('config');
    $block = new JFX_Block;

    $blockDetails['elements'] = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}blocks WHERE page_id = '{$pageid}' AND workspace_id = '{$workspaceid}' AND parent_id = '{$blockDetails['id']}'");

    $installedLangs = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}languages");

    $lang = array();
    foreach($installedLangs as $k=>$v){
        $langContent = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}lang_content WHERE item_id = '{$blockDetails['id']}' AND lang = '{$v['keyname']}'");
        $lang[$v['keyname']] = $langContent;
    }
    $blockDetails['lang'] = $lang;
    foreach($blockDetails['elements'] as $k=>$v){
        $blockDetails['elements'][$k] = JFX_ExportBlock_GetBlockDetails($v, $pageid, $workspaceid);
    }
    if(!is_array($blockDetails)) $blockDetails = array();
    return $blockDetails;
}














function JFX_ImportBlock_ImportBlocks($details, $pageid){



    $DB = JFX::registry('db');
    $USER = JFX::registry('JFX_User');
    $CONFIG = JFX::registry('config');
    $BWT = JFX::registry('ThirdParty_BWT');
    $MTF = JFX::registry('ThirdParty_MTF');
    $LANG = JFX::registry('lang');
    $block = new JFX_Block;

    $installedLangs = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}languages");

    $subblocks = $details['elements'];

    if(!is_array($subblocks)) $subblocks = array();

    $details['page_id'] = $pageid;
    $blockid = $details['id'];
    $blockids = explode('-', $blockid);
    $blockid = 'jfxpage-'.$pageid.'-'.$blockids[2].'-'.$blockids[3];
    $currentBlockIdCount = $blockids[3];

    while($DB->countRows($CONFIG->dbprefix.'blocks', "id = '{$blockid}' AND page_id = '{$pageid}'")>0){
        // generate a unique id
        $currentBlockIdCount++;
        $blockid = 'jfxpage-'.$pageid.'-'.$blockids[2].'-'.($currentBlockIdCount);
    }

    $details['id'] = $blockid;
    $details['page_id'] = $pageid;
    $details['workspace_id'] = $USER->workspace;
    $details['parent_id'] = $parentBlockid;
    $block->setDetails($details);
    $block->save();

    $lang = $details['lang'];

    if(is_array($lang)){
        foreach($installedLangs as $key=>$value){
            if(array_key_exists($value['keyname'], $lang)) $blockLangs = $lang[$value['keyname']];
            else{
                foreach($installedLangs as $langkeyname=>$vv) break;
                $blockLangs = $lang[$langkeyname];
            }
            foreach($blockLangs as $blockLangKey=>$thisLang){
                $dbParams = array(
                    'module_key' => $thisLang['module_key'],
                    'label' => $thisLang['label'],
                    'lang' => $value['keyname'],
                    'item_id' => $blockid,
                    'workspace_id' => $USER->workspace,
                    'v' => $thisLang['v']
                );
                $DB->insert($CONFIG->dbprefix.'lang_content', $dbParams);
            }
        }

    }

    foreach($subblocks as $key=>$value){
        JFX_ImportBlock_ImportBlocks($value, $pageid, $blockid);
    }
}



































function JFX_ImportBlock_MakeTree($arr, $idPrefix='page_', $workspaceid=''){
    $CONFIG = JFX::registry('config');
    $LANG = JFX::registry('lang');
    $USER = JFX::registry('JFX_User');
    if($workspaceid == '') $workspaceid = $USER->workspace;
    $returnString = '';
    foreach($arr as $k=>$v){

        $link = '<a href="javascript: void(null)" id="'.$idPrefix.$v['id'].'">'.$LANG->getContent('core', 'page_title', $v['id'], '', $workspaceid).'</a>';
        if(isset($v['subpages']) && count($v['subpages'])>0){
            $subpages = '<ul>'.JFX_ImportBlock_MakeTree($v['subpages'], $idPrefix, $workspaceid).'</ul>';
        }else{
            $subpages = '';
        }
        $returnString .= '<li>'.$link.$subpages.'</li>';
    }

    return $returnString;
}








function JFX_ImportPage_DecompressPage($page, $parentid, $domainid){
    $DB = JFX::registry('db');
    $USER = JFX::registry('JFX_User');
    $CONFIG = JFX::registry('config');
    $BWT = JFX::registry('ThirdParty_BWT');
    $MTF = JFX::registry('ThirdParty_MTF');
    $LANG = JFX::registry('lang');
    $block = new JFX_Block;


    $domainid = $DB->oneValue($CONFIG->dbprefix.'pages', 'domain_id', "id = '{$parentid}'");

    $newPage = array();
    $newPage['id'] = $page['i'];
    $newPage['parent_id'] = $parentid;
    $newPage['slug'] = $page['s'];
    $newPage['is_published'] = $page['l'];
    $newPage['owner_id'] = $page['o'];
    $newPage['created_tstamp'] = $page['c'];
    $newPage['modified_tstamp'] = $page['m'];

    $newPage['domain_id'] = $domainid;
    $newPage['workspace_id'] = $USER->workspace;


    // get a unique slug
    $slug = $newPage['slug'];
    while($DB->countRows($CONFIG->dbprefix.'pages', "slug = '{$slug}' AND workspace_id = '{$USER->workspace}' AND domain_id = '{$domainid}'")>0){
        $slug .= '1';
    }
    $newPage['slug'] = $slug;

    unset($newPage['id']);
    $pageid = $DB->insert($CONFIG->dbprefix.'pages', $newPage);

    $newPage['id'] = $pageid;
    $params = array(
        'page_id' => $pageid,
        'module_data' => $page['md']
    );

    JFX::hook('JFX_Core.importPage', $params);

    // languages
    $langs = $page['t'];
    $installedLangs = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}languages");

    foreach($installedLangs as $k=>$v){
        if(array_key_exists($v['keyname'], $langs)) $lang = $langs[$v['keyname']];
        else{
            foreach($langs as $langKey=>$vv) break;
            $lang = $langs[$langKey];
        }

        $LANG->updateContent('core', 'page_title', $pageid, $lang['t'], $v['keyname'], $USER->workspace);
        $LANG->updateContent('core', 'page_menu', $pageid, $lang['m'], $v['keyname'], $USER->workspace);
        $LANG->updateContent('core', 'page_content', $pageid, $lang['c'], $v['keyname'], $USER->workspace);
    }

    if(count($page['sp'])>0){
        foreach($page['sp'] as $k=>$v){
            JFX_ImportPage_DecompressPage($v, $pageid, $domainid);
        }
    }

    $blocks = unserialize($page['b']);

    foreach($blocks as $k=>$v){
        JFX_ImportPage_ImportBlocks($v, $pageid, 'jfxpage-'.$pageid);
    }
}




function JFX_ImportPage_ImportBlocks($details, $pageid, $parentBlockid){



    $DB = JFX::registry('db');
    $USER = JFX::registry('JFX_User');
    $CONFIG = JFX::registry('config');
    $BWT = JFX::registry('ThirdParty_BWT');
    $MTF = JFX::registry('ThirdParty_MTF');
    $LANG = JFX::registry('lang');
    $block = new JFX_Block;

    $installedLangs = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}languages");

    $subblocks = $details['elements'];

    if(!is_array($subblocks)) $subblocks = array();

    $details['page_id'] = $pageid;
    $blockid = $details['id'];
    $blockids = explode('-', $blockid);
    $blockid = 'jfxpage-'.$pageid.'-'.$blockids[2].'-'.$blockids[3];


    $details['id'] = $blockid;
    $details['page_id'] = $pageid;
    $details['workspace_id'] = $USER->workspace;
    $details['parent_id'] = $parentBlockid;
    $block->setDetails($details);
    $block->save();

    $params = array(
        'block_id' => $block->id,
        'module_data' => $details['md']
    );

    JFX::hook('JFX_Core.importBlock', $params);

    $lang = $details['lang'];

    if(is_array($lang)){
        foreach($lang as $defaultLang=>$v) break;

        foreach($installedLangs as $key=>$value){

            if(array_key_exists($value['keyname'], $lang)) $blockLangs = $lang[$value['keyname']];
            else $blockLangs = $lang[$defaultLang];

            foreach($blockLangs as $blockLangKey=>$thisLang){

                $LANG->updateContent($thisLang['module_key'], $thisLang['label'], $blockid, $thisLang['v'], $value['keyname'], $USER->workspace);
                /*
                $dbParams = array(
                    'module_key' => $thisLang['module_key'],
                    'label' => $thisLang['label'],
                    'lang' => $value['keyname'],
                    'item_id' => $blockid,
                    'workspace_id' => $USER->workspace,
                    'v' => $thisLang['v']
                );
                echo "INSERT INTO {$CONFIG->dbprefix}lang_content {$blockid}, {$thisLang['module_key']}, {$thisLang['label']}, {$thisLang['v']}<br />";
                $DB->insert($CONFIG->dbprefix.'lang_content', $dbParams);*/
            }
        }

    }

    foreach($subblocks as $key=>$value){
        JFX_ImportPage_ImportBlocks($value, $pageid, $blockid);
    }
}








function JFX_ImportPage_MakeTree($arr, $idPrefix='page_', $workspaceid=1){
    $CONFIG = JFX::registry('config');
    $LANG = JFX::registry('lang');
    $returnString = '';
    foreach($arr as $k=>$v){

        $link = '<a href="javascript: void(null)" id="'.$idPrefix.$v['id'].'">'.$LANG->getContent('core', 'page_title', $v['id'], '', $workspaceid).'</a>';
        if(isset($v['subpages']) && count($v['subpages'])>0){
            $subpages = '<ul>'.JFX_ImportPage_MakeTree($v['subpages'], $idPrefix, $workspaceid).'</ul>';
        }else{
            $subpages = '';
        }
        $returnString .= '<li>'.$link.$subpages.'</li>';
    }

    return $returnString;
}





function JFXAdmin_ImportTemplate_ImportBlocks($pageid, $parentBlockId, $divs, $isTemplate=false){
    $DB = JFX::registry('db');
    $CONFIG = JFX::registry('config');
    $LANG = JFX::registry('lang');

    foreach($divs->elements as $k=>$v){
        $module = strtolower(trim($v->getAttribute('module')));
        $action = strtolower(trim($v->getAttribute('action')));
        $class = trim($v->getAttribute('class'));
        $title = trim($v->getAttribute('title'));

        if($module == '' || !JFX_Module::isValidModule($module)) $module = 'content';
        if($action == '' || !JFX_Module::isValidAction($module, $action)) $action = 'content';

        $incrementor = $DB->oneValue($CONFIG->dbprefix.'blocks', 'COUNT(*)', "page_id = '{$pageid}' AND workspace_id = 1 AND module_key = '{$module}'");
        $incrementor++;

        if($title == '') $title = $module.':'.$action.'.'.$incrementor;

        $dbParams = array(
            'id' => 'jfxpage-'.$pageid.'-'.$module.'-'.$incrementor,
            'module_key' => $module,
            'module_action' => $action,
            'parent_id' => $parentBlockId,
            'page_id' => $pageid,
            'workspace_id' => 1,
            'sorting' => 0,
            'exec_order' => 0,
            'page_parent' => 1,
            'class_name' => $class,
            'is_droppable' => 0,
            'is_template' => (int) $isTemplate,
            'template' => '',
            'block_style' => ''
        );

        $newParentBlockId = 'jfxpage-'.$pageid.'-'.$module.'-'.$incrementor;
        $isTemplate = false;

        $DB->insert($CONFIG->dbprefix.'blocks', $dbParams);

        $LANG->updateContent('core', 'block_title', $newParentBlockId, $title, '*', 1);

        $hookParams = array(
            'block_id' => $newParentBlockId,
            'element' => $v
        );
        JFX::hook('JFX_Core.importTemplate', $hookParams);

        // child divs
        $childDivs = pq('>div', $v);

        JFXAdmin_ImportTemplate_ImportBlocks($pageid, $newParentBlockId, $childDivs, false);


    }
}






















